package cn.javabb.common.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author javabb
 * @Date 2019/8/8 0008 下午 7:30
 * @Desc
 */
@Slf4j
public class HttpUtil {
    public static final String CHARSET = "UTF-8";
    //读取超时 单位毫秒
    public static final int ReadTimeout = 1000*60*5;//5分钟
    //连接超时 单位毫秒
    public static final int ConnectTimeout = 1000*60*6;//6分钟

    /**
     * Description:
     *  <pre>
     *  get方式获取指定路径下的接口数据
     *  </pre>
     * @author javabb
     * @param url  需要请求的路径,外部的地址必须使用全路径,内部路径将进行处理,补充前缀内容.包含http://或https://(https不一定有效,未测试)
     * @param params 请求的参数
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {
        if (StrUtil.isBlank(url)) {
            return null;
        }
        try {
            StringBuilder sb = new StringBuilder();
            if(params!=null&&params.size()>0){
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String key=entry.getKey();
                    String value=entry.getValue()+"";
                    if(BUtil.isChinese(value) || value.contains(" ")){
                        value = URLEncoder.encode(value, "UTF-8");
                    }
                    sb.append(key+"="+value+"&");
                }
                if(sb.length()>0){
                    sb.replace(sb.length()-1, sb.length(), "");
                }
                if(url.contains("?")){
                    url=url+"&"+sb.toString();
                }else{
                    url=url+"?"+sb.toString();
                }
            }


            URL httpUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setConnectTimeout(ConnectTimeout);
            connection.setReadTimeout(ReadTimeout);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, CHARSET));
            StringBuffer sbf = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
            }
            reader.close();
            String result = sbf.toString();
            connection.disconnect();
            return result;
        } catch (Exception e) {
            System.out.println("===========================");
            System.out.println(url);
            System.out.println("调用接口失败："+e.getMessage());
            System.out.println("===========================");
        }
        return null;
    }



    /**
     * HTTP Post 获取内容
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, Object> params) {
        if (StrUtil.isBlank(url)) {
            return null;
        }
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setConnectTimeout(ConnectTimeout);
            connection.setReadTimeout(ReadTimeout);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "UTF-8");
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            StringBuilder sb = new StringBuilder();
            if(params!=null&&params.size()>0){
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String key=entry.getKey();
                    String value=entry.getValue()+"";
                    sb.append(key+"="+value+"&");
                }
                if(sb.length()>0){
                    sb.replace(sb.length()-1, sb.length(), "");
                }
            }

            out.writeBytes(sb.toString());// 输入参数
            out.flush();
            out.close();

            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, CHARSET));
            StringBuffer sbf = new StringBuffer();
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
            }
            reader.close();
            String result = sbf.toString();
            connection.disconnect();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
